package com.chinacoal.microservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.plugins.Page;
import com.chinacoal.microservice.mapper.CcmsSmartleasingBasicdataMapper;
import com.chinacoal.microservice.mapper.CcmsSmartleasingDeviceManagementMapper;
import com.chinacoal.microservice.pojo.BasicConfiguration;
import com.chinacoal.microservice.pojo.CcmsSmartleasingDeviceManagement;
import com.chinacoal.microservice.pojo.Currency;
import com.chinacoal.microservice.service.DeviceManagementService;
import com.chinacoal.microservice.util.CodeMsg;
import com.chinacoal.microservice.util.QueryCriteria;
import com.chinacoal.microservice.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author zhuliang
 * @version V1.0
 * @Description: 运维管理-设备管理-后端实现类
 * @date 2020-12-17 10：55
 */
@Slf4j
@Service
public class DeviceManagementServiceImpl implements DeviceManagementService {

    @Autowired
    private CcmsSmartleasingDeviceManagementMapper deviceManagementMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private BasicConfiguration basicConfiguration;

    @Autowired
    private CcmsSmartleasingBasicdataMapper basicdataMapper;

    /**
     * @Description: 查询所有的设备信息（带分页）
     * @author zhuliang
     * @date 2020/12/17 11:22
     */
    @Override
    public Result<List<CcmsSmartleasingDeviceManagement>> getAllByPage(QueryCriteria queryCriteria, String token) {
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //设置分页条件
        Page<CcmsSmartleasingDeviceManagement> toPage = new Page<>(queryCriteria.getPage(), queryCriteria.getPageSize());

        //开始分页查询
        List<CcmsSmartleasingDeviceManagement> deviceManagements = deviceManagementMapper.getAllByPage(toPage,
                                                                                                        currency.getProperty(),
                                                                                                        currency.getManagementOffice());

        return Result.success(deviceManagements, toPage.getTotal());
    }

    /**
     * @Description: 条件查询所有的设备信息（带分页）
     * @author zhuliang
     * @date 2020/12/17 11:22
     */
    @Override
    public Result<List<CcmsSmartleasingDeviceManagement>> getAllByCondition(QueryCriteria queryCriteria, String token) {
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //设置分页条件
        Page<CcmsSmartleasingDeviceManagement> toPage = new Page<>(queryCriteria.getPage(), queryCriteria.getPageSize());

        //开始条件分页查询
        List<CcmsSmartleasingDeviceManagement> deviceManagements = deviceManagementMapper.getAllByCondition(toPage,
                                                                                                            queryCriteria.getEquipmentSerialNumber(),
                                                                                                            queryCriteria.getBrand(),
                                                                                                            queryCriteria.getRegion(),
                                                                                                            queryCriteria.getFkEquipmentTypeId(),
                                                                                                            queryCriteria.getEquipmentName(),
                                                                                                            queryCriteria.getFkBuildingId(),
                                                                                                            currency.getProperty(),
                                                                                                            currency.getManagementOffice());

        return Result.success(deviceManagements, toPage.getTotal());
    }

    /**
     * @Description: 根据设备id查询设备信息
     * @author zhuliang
     * @date 2020/12/17 14:30
     */
    @Override
    public Result<CcmsSmartleasingDeviceManagement> getDeviceById(String pkDeviceManagementId, String token) {
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //根据id查询设备信息
        CcmsSmartleasingDeviceManagement deviceManagement = deviceManagementMapper.getDeviceById(pkDeviceManagementId,
                                                                                                currency.getProperty(),
                                                                                                currency.getManagementOffice());

        //兼容性判断
        if (null == deviceManagement) {
            log.error(CodeMsg.NOT_FOUND.toString() + "-->此设备信息无权限访问，或数据丢失-->" + pkDeviceManagementId);
            return Result.error(CodeMsg.NOT_FOUND);
        }

        return Result.success(deviceManagement);
    }

    /**
     * @Description: 修改设备信息
     * @author zhuliang
     * @date 2020/12/17 14:30
     */
    @Override
    public Result updateByDevice(CcmsSmartleasingDeviceManagement deviceManagement, String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

//        //验证序列号的唯一性
//        String numberUniqueness = deviceManagementMapper.serialNumberUniqueness(deviceManagement.getEquipmentSerialNumber());
//        if (StringUtils.isNotBlank(numberUniqueness)) {
//            log.error(CodeMsg.SERIAL_NUMBER_ALREADY_EXISTS.toString() + "-->序列号：" + deviceManagement.getEquipmentSerialNumber());
//            return Result.error(CodeMsg.SERIAL_NUMBER_ALREADY_EXISTS);
//        }
//
//        if ("weiyu.circuit_breaker".equals(deviceManagement.getFkEquipmentTypeId())) {
//            //线路唯一性验证
//            String s = deviceManagementMapper.uniquenessVerification(deviceManagement.getLine(), deviceManagement.getRegion(), null);
//
//            if (StringUtils.isNotBlank(s)) {
//                log.error(CodeMsg.LINE_ALREADY_IS_USE.toString() + "-->区域：" + deviceManagement.getRegion() + "-->线路：" + deviceManagement.getLine());
//                return Result.error(CodeMsg.LINE_ALREADY_IS_USE);
//            }
//
//            deviceManagement.setDeviceStatus(new Byte("0"));
//        }

        //修改类的最后修改时间
        deviceManagement.setLastUpdateDate(new Date());
        deviceManagement.setLastUpdatedBy(currency.getLoginId());

        //修改设备信息
        deviceManagementMapper.updateById(deviceManagement);

        return Result.success();
    }

    /**
     * @Description: 添加设备信息
     * @author zhuliang
     * @date 2020/12/17 14:30
     */
    @Override
    public Result addByDevice(CcmsSmartleasingDeviceManagement deviceManagement, String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //验证序列号的唯一性
        String numberUniqueness = deviceManagementMapper.serialNumberUniqueness(deviceManagement.getEquipmentSerialNumber());
        if (StringUtils.isNotBlank(numberUniqueness)) {
            log.error(CodeMsg.SERIAL_NUMBER_ALREADY_EXISTS.toString() + "-->序列号：" + deviceManagement.getEquipmentSerialNumber());
            return Result.error(CodeMsg.SERIAL_NUMBER_ALREADY_EXISTS);
        }

        String type = deviceManagement.getFkEquipmentTypeId();
        if ("weiyu.circuit_breaker".equals(type)) {
            //线路唯一性验证
            String s = deviceManagementMapper.uniquenessVerification(deviceManagement.getLine(), deviceManagement.getRegion(), deviceManagement.getFkBuildingId(),null);

            if (StringUtils.isNotBlank(s)) {
                log.error(CodeMsg.LINE_ALREADY_IS_USE.toString() + "-->区域：" + deviceManagement.getRegion() + "-->线路：" + deviceManagement.getLine());
                return Result.error(CodeMsg.LINE_ALREADY_IS_USE);
            }

            deviceManagement.setDeviceStatus(new Byte("0"));
        }else if ("lumi".equals(type.split("\\.")[0])) {
            //判断是否是同一种设备
            String deviceModel = basicdataMapper.queryDeviceModel(type, deviceManagement.getEquipmentTypeName());

            if (StringUtils.isBlank(deviceModel)) {
                log.error(CodeMsg.DEVICE_MODEL_DOES_NOT_MATCH.toString() + "-->获取类型:" + deviceManagement.getEquipmentTypeName() + "-->选择类型：" + type);
                return Result.error(CodeMsg.DEVICE_MODEL_DOES_NOT_MATCH);
            }
        }

        //完善信息
        deviceManagement.setLastUpdatedBy(currency.getLoginId());
        deviceManagement.setLastUpdateDate(new Date());
        deviceManagement.setCreatedBy(currency.getLoginId());
        deviceManagement.setCreationDate(new Date());
        deviceManagement.setPkDeviceManagementId(UUID.randomUUID() + "");

        //添加设备信息
        deviceManagementMapper.insert(deviceManagement);

        return Result.success();
    }

    /**
     * @Description: 获取云丁的token的路径信息
     * @author zhuliang
     * @date 2021/2/1 16:10
     */
    @Override
    public Result getYunDingTokenUrl() {
        //从redis中获取云丁的token
        String yunDingToken = redisTemplate.opsForValue().get("yunDingToken") + "";

        HashMap<String, Object> map = new HashMap<>();
        //判断是否有，或者过期
        if (null == yunDingToken || "".equals(yunDingToken) || "null".equals(yunDingToken)) {

            map.put("url", "/yunDing");   //nginx代理
            map.put("client_id", basicConfiguration.getClientId());
            map.put("client_secret", basicConfiguration.getClientSecret());
            map.put("yunDingToken", null);
        } else {
            map.put("yunDingToken", yunDingToken);
        }

        return Result.success(map);
    }

    /**
     * @Description: 获取微羽的token的路径信息
     * @author zhuliang
     * @date 2021/2/1 16:10
     */
    @Override
    public Result getWeiYuTokenUrl() {
        //获取redis中的微羽的token
        String weiYuToken = redisTemplate.opsForValue().get("weiYuToken") + "";
        HashMap<String, Object> map = new HashMap<>();

        if (null == weiYuToken || "".equals(weiYuToken) || "null".equals(weiYuToken)) {
            //设置请求参数
            String url = null;
            try {
                //nginx代理
                url = "/weiYu?clientid=" + basicConfiguration.getWeiYuClientId() +
                        "&secret=" + basicConfiguration.getWeiYuSecret() + "&scope=" + URLEncoder.encode("api smarthome", "utf-8");
            } catch (UnsupportedEncodingException e) {
                log.error(CodeMsg.IllegalArgumentException.toString() + "-->" + e);
                return Result.error(CodeMsg.IllegalArgumentException);
            }

            map.put("weiYuToken", null);
            map.put("url", url);
        }else {
            map.put("weiYuToken", weiYuToken);
        }

        return Result.success(map);
    }

    /**
     * @Description: 获取绿米的token的路径信息
     * @author zhuliang
     * @date 2021/2/1 16:10
     */
    @Override
    public Result getLuMiTokenUrl(String code) {
        HashMap<String, Object> map = new HashMap<>();
        HashMap<String, String> parameterMap = new HashMap<>();
        HashMap<String, String> inquireMap = new HashMap<>();

        if (null == code){
            map.put("luMiAccessTokenUrl", null);

            //从redis中获取绿米的token
            String luMiAccessToken = redisTemplate.opsForValue().get("luMiAccessToken") + "";

            //判断是否过期
            if (null == luMiAccessToken || "".equals(luMiAccessToken) || "null".equals(luMiAccessToken)) {
                map.put("luMiAccessToken", null);

                //获取绿米的刷新token
                String luMiRefreshToken = redisTemplate.opsForValue().get("luMiRefreshToken") + "";

                //判断刷新token是否为空
                if (null == luMiRefreshToken || "".equals(luMiRefreshToken) || "null".equals(luMiRefreshToken)) {
                    map.put("luMiRefreshTokenUrl", null);
                    map.put("codeUrl", "/luMi");    //nginx代理

                    parameterMap.put("clientId", basicConfiguration.getLuMiClientId());
                    parameterMap.put("responseType", "code");
                    parameterMap.put("redirectUri", basicConfiguration.getLuMiRedirectUri());
                    parameterMap.put("account", basicConfiguration.getLuMiAccount());
                    parameterMap.put("password", basicConfiguration.getLuMiPassWord());

                    map.put("codeParameter", JSONObject.toJSONString(parameterMap));

                } else {
                    //获取token参数
                    parameterMap.put("client_id", basicConfiguration.getLuMiClientId());
                    parameterMap.put("client_secret", basicConfiguration.getLuMiClientSecret());
                    parameterMap.put("redirect_uri", basicConfiguration.getLuMiRedirectUri());
                    parameterMap.put("grant_type", "refresh_token");
                    parameterMap.put("refresh_token", luMiRefreshToken);

                    //查询设备信息参数
                    inquireMap.put("Appid", basicConfiguration.getLuMiClientId());
                    inquireMap.put("Time", System.currentTimeMillis() + "");

                    map.put("luMiAccessTokenUrl", "/tokenLuMi");
                    map.put("codeUrl", null);
                    map.put("codeParameter", null);
                    map.put("parameterMap", parameterMap);
                    map.put("inquireUrl", "/queryLuMi");
                    map.put("inquireMap", inquireMap);
                }

            }else {
                //查询设备信息参数
                inquireMap.put("Appid", basicConfiguration.getLuMiClientId());
                inquireMap.put("Time", System.currentTimeMillis() + "");

                map.put("luMiAccessToken", luMiAccessToken);
                map.put("inquireUrl", "/queryLuMi");
                map.put("inquireMap", inquireMap);
            }
        } else {
            //获取token参数
            parameterMap.put("client_id", basicConfiguration.getLuMiClientId());
            parameterMap.put("client_secret", basicConfiguration.getLuMiClientSecret());
            parameterMap.put("redirect_uri", basicConfiguration.getLuMiRedirectUri());
            parameterMap.put("grant_type", "authorization_code");
            parameterMap.put("code", code);

            //查询设备信息参数
            inquireMap.put("Appid", basicConfiguration.getLuMiClientId());
            inquireMap.put("Time", System.currentTimeMillis() + "");

            map.put("luMiAccessTokenUrl", "/tokenLuMi");
            map.put("parameterMap", parameterMap);
            map.put("inquireUrl", "/queryLuMi");
            map.put("inquireMap", inquireMap);
        }

        return Result.success(map);
    }

    /**
     * @Description: 存放第三方设备token信息
     * @author zhuliang
     * @date 2021/2/1 16:51
     */
    @Override
    public Result getThirdPartyToken(String yunDingToken, String weiYuToken, String luMiAccessToken, String luMiRefreshToken) {
        if (StringUtils.isNotBlank(yunDingToken)) {

            redisTemplate.opsForValue().set("yunDingToken", yunDingToken, 29,TimeUnit.DAYS);

        } else if (StringUtils.isNotBlank(weiYuToken)) {

            redisTemplate.opsForValue().set("weiYuToken", weiYuToken, 6,TimeUnit.DAYS);

        } else if (StringUtils.isNotBlank(luMiAccessToken)) {

            redisTemplate.opsForValue().set("luMiAccessToken", luMiAccessToken, 23, TimeUnit.HOURS);

        } else if (StringUtils.isNotBlank(luMiRefreshToken)){

            redisTemplate.opsForValue().set("luMiRefreshToken", luMiRefreshToken, 29, TimeUnit.DAYS);

        } else {

            log.error(CodeMsg.NOT_FOUND.toString() + "token:" + yunDingToken + "-" + weiYuToken + "-" + luMiAccessToken + "-" + luMiRefreshToken);
            Result.error(CodeMsg.NOT_FOUND);

        }

        return Result.success();
    }
}
